package com.sqfw.project.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;


/**
 * 通过FTP上传文件
 *
 */
@Component
@PropertySource(value = {"classpath:ftp.properties"}, encoding = "utf-8")
@Slf4j
public class FTPTools {

    //设置私有不能实例化
    private FTPTools() {
    }
    
    public static String host;
    private static int port;
    private static String username;
    private static String password;
    private static String workingPath;

    public static String getHost() {
        return host;
    }

    public static int getPort() {
        return port;
    }

    public static String getUsername() {
        return username;
    }

    public static String getPassword() {
        return password;
    }

    public static String getWorkingPath() {
        return workingPath;
    }

    public static Logger getLog() {
        return log;
    }

    @Value("${ftp.host}")
    public void setHost(String host){
        FTPTools.host = host;
    }
    @Value("${ftp.port}")
    public void setPort(int port){
        FTPTools.port = port;
    }
    @Value("${ftp.username}")
    public void setUsername(String username){
        FTPTools.username = username;
    }
    @Value("${ftp.password}")
    public void setPassword(String password){
        FTPTools.password = password;
    }
    @Value("${ftp.workingPath}")
    public void setWorkingPath(String workingPath){
        FTPTools.workingPath = workingPath;
    }
    
    public static boolean upload(InputStream inputStream, String saveName, String dir) {
        boolean flag = false;
        FTPClient ftpClient = new FTPClient();
        //1 测试连接
        if (connect(ftpClient, host, port, username, password)) {
            try {
                String path = workingPath + dir;
                System.out.println(path);
                String[] split = path.split("/");
                for (String str : split) {
                    if(StringUtils.isEmpty(str)){
                        continue;
                    }
                    //FTP创建文件夹需要循环创建
                    //2 检查工作目录是否存在
                    if (!ftpClient.changeWorkingDirectory(str)) {
                        boolean b = ftpClient.makeDirectory(str);
                        ftpClient.changeWorkingDirectory(str);
                    }
                }

                // 3 检查是否上传成功
                if (storeFile(ftpClient, saveName, inputStream)) {
                    flag = true;
                    disconnect(ftpClient);
                }
            } catch (IOException e) {
                log.error("工作目录不存在");
                e.printStackTrace();
                disconnect(ftpClient);
            }
        }
        return flag;
    }

    /**
     * 断开连接
     *
     * @param ftpClient
     * @throws Exception
     */
    public static void disconnect(FTPClient ftpClient) {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
                log.info("已关闭连接");
            } catch (IOException e) {
                log.error("没有关闭连接");
                e.printStackTrace();
            }
        }
    }

    /**
     * 测试是否能连接
     *
     * @param ftpClient
     * @param hostname  ip或域名地址
     * @param port      端口
     * @param username  用户名
     * @param password  密码
     * @return 返回真则能连接
     */
    public static boolean connect(FTPClient ftpClient, String hostname, int port, String username, String password) {
        boolean flag = false;
        try {
            //ftp初始化的一些参数
            ftpClient.connect(hostname, port);
            if (ftpClient.login(username, password)) {
                log.info("连接ftp成功");
                ftpClient.setBufferSize(1024);
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.setControlEncoding("UTF-8");
                flag = true;
            } else {
                log.error("连接ftp失败，可能用户名或密码错误");
                try {
                    disconnect(ftpClient);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            log.error("连接失败，可能ip或端口错误");
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 上传文件
     *
     * @param ftpClient
     * @param saveName        全路径。如/home/public/a.txt
     * @param fileInputStream 要上传的文件流
     * @return
     */
    public static boolean storeFile(FTPClient ftpClient, String saveName, InputStream fileInputStream) {
        boolean flag = false;
        try {
            if (ftpClient.storeFile(saveName, fileInputStream)) {
                flag = true;
                log.info("上传成功");
                disconnect(ftpClient);
            }
        } catch (IOException e) {
            log.error("上传失败");
            disconnect(ftpClient);
            e.printStackTrace();
        }
        return flag;
    }
}


